package com.withmiku.world.user.service.impl;

import com.withmiku.world.user.entity.Post;
import com.withmiku.world.user.entity.PostImage;
import com.withmiku.world.user.repository.PostImageRepository;
import com.withmiku.world.user.repository.PostRepository;
import com.withmiku.world.user.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PostServiceImpl implements PostService {
    private final PostRepository postRepository;
    private final PostImageRepository postImageRepository;

    @Autowired
    public PostServiceImpl(PostRepository postRepository, PostImageRepository postImageRepository) {
        this.postRepository = postRepository;
        this.postImageRepository = postImageRepository;
    }

    @Transactional
    @Override
    public Post createPost(Post post) {
        // 保存主表
        Post savedPost = postRepository.save(post);

        // 如果有图片，一起保存
        List<PostImage> images = post.getImages();
        if (images != null && !images.isEmpty()) {
            for (PostImage image : images) {
                image.setPost(savedPost);
            }
            postImageRepository.saveAll(images);
        }

        return savedPost;
    }

    @Override
    public Page<Post> listPosts(int page, int size) {
        // 注意page从0开始是第一页，需要在控制层进行前后端兼容处理
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");

        return postRepository.findAllByOrderByCreateTimeDesc(pageable);
    }

    @Override
    public Post getPostById(Long id) {
        return postRepository.findById(id).orElseThrow(
                () -> new RuntimeException("动态不存在")
        );
    }

    @Override
    public Page<Post> getUserPosts(Long userId, int page, int size) {
        if (userId == null) {
            throw new IllegalArgumentException("userId required");
        }
        // 注意page从0开始是第一页，需要在控制层进行前后端兼容处理
        Pageable pageable = PageRequest.of(
                page,
                size,
                Sort.by(Sort.Direction.DESC, "createTime")
        );

        return postRepository.findByUserIdOrderByCreateTimeDesc(userId, pageable);
    }
}
